package sufutian.com.englishvoicetrans;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;

import java.io.File;
import java.io.InputStream;

import sufutian.com.englishvoicetrans.FireBaseStorage.FireBaseDemo;

public class MainActivity extends AppCompatActivity {


    private String TAG = "MainActivity";

    EnglishVoiceClient2.EnglishTransListener listener = new EnglishVoiceClient2.EnglishTransListener() {
        @Override
        public void onSpeechRecognized(final String text, boolean isFinal) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (text != null) {
                        textview.setText(text + textview.getText());
                    }
                    Log.e("sufutian==", "onSpeechRecognized: " + text);
                }
            });
        }
    };

    private TextView textview;
    private EnglishVoiceClient client;
    private InputStream inputStream;

    private FireBaseDemo fireBaseDemo;
    private GoogleSignInOptions signInOptions;
    private GoogleApiClient mGoogleApiClient;


    private int RC_SIGN_IN = 0x110;

    private FirebaseAuth mAuth;

    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview = (TextView) findViewById(R.id.textView);

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                } else { // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
            }
        };


//        auth();


//        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/sufutian" + "/sufutian.wav");
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/sufutian" + "/paigo1.wav");
//        if (file.exists()) {
//            try {
//                inputStream = new FileInputStream(file);
//
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//        }

        inputStream = getResources().openRawResource(R.raw.audio);
//        inputStream = getResources().openRawResource(R.raw.test);

        client = new EnglishVoiceClient(MainActivity.this);


        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                client.recognizeInputStream(inputStream, false);
                auth();
            }
        });

        findViewById(R.id.start_long).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                client.recognizeInputStream(inputStream, true);
            }
        });


        findViewById(R.id.record).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioUtil.getInstance().startRecord();
                AudioUtil.getInstance().recordData();

            }
        });
        findViewById(R.id.stop_record).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioUtil.getInstance().stopRecord();
                AudioUtil.getInstance().convertWaveFile();
            }
        });

        findViewById(R.id.upload_storage).setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                fireBaseDemo = new FireBaseDemo(MainActivity.this);
            }
        });

        findViewById(R.id.delete_storage).setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                fireBaseDemo.deleteFile();
            }
        });

        mAuth = FirebaseAuth.getInstance();


        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

    }

    //身份认证

    private void auth() {
// Configure Google Sign In
        signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken("644780607212-ul84akoj76hqu7h8hq3d3edm83rrvd3i.apps.googleusercontent.com")
                .requestEmail()
                .build();

        /* FragmentActivity *//* OnConnectionFailedListener */
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        Toast.makeText(MainActivity.this, "onConnectionFailed failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions)
                .build();


        signIn();

    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        client.removeListener(listener);

        FirebaseAuth.getInstance().signOut();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            firebaseAuthWithGoogle(acct);
        } else {
            // Signed out, show unauthenticated UI.

        }
    }


    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();

                        }

                    }
                });
    }

}
